#include "AsyncLogger.h"
#include <Arduino.h> // Include the Arduino header for HardwareSerial


QueueHandle_t printQueue = NULL;

void asyncPrintTask(void *parameter) 
{
    while (1) 
    {
        char *message = NULL;
        if(xQueueReceive(printQueue, &message, portMAX_DELAY))
        {
            if (message != NULL) 
            {
                Serial.print(message);
                free(message); // 释放动态分配的内存
            }
        }
        //vTaskDelay(pdMS_TO_TICKS(1)); // 非阻塞，释放CPU给其他任务
    }
}

void setupAsyncPrint(void) {
    printQueue = xQueueCreate(PRINT_QUEUE_SIZE, sizeof(char *));
    xTaskCreate(asyncPrintTask, "AsyncPrintTask", PRINT_TASK_STACK_SIZE, NULL, PRINT_TASK_PRIORITY, NULL);
}

void asyncPrint(const char *format, ...) {
    va_list args;
    va_start(args, format);
    
    // 计算需要的缓冲区大小
    int size = vsnprintf(NULL, 0, format, args) + 1;
    va_end(args);
    
    if (size <= 0) return;
    
    // 动态分配内存
    char *buffer = (char *)malloc(size);
    if (buffer == NULL) return;
    
    va_start(args, format);
    vsnprintf(buffer, size, format, args);
    va_end(args);
    
    // 发送到打印队列
    if (xQueueSend(printQueue, &buffer, 0) != pdPASS) {
        free(buffer); // 如果队列已满，释放内存
    }
}
